﻿using UnityEngine;

namespace Game
{
    public class ScenePlayerEntity : SceneMovableEntity
    {
        private PlayerConfigData _playerData;
        private Transform _spriteTransform;
        private SpriteRenderer _spriteRenderer;
        private ScenePlayerBehaviorComponent _behaviorComponent;
        private ScenePetEntity _scenePet;
        
        public ScenePlayerEntity(int id) : base(id, SceneObjectEntityType.Player)
        {
        }

        public void LoadPlayer(int configId)
        {
            if (_playerData != null && _playerData.id == configId)
            {
                return;
            }

            _playerData = ConfigSystem.Instance.Get<PlayerConfigEntity>().GetData(configId);
            Load(_playerData.url);
        }
        
        public override void SetFlipX(bool flip)
        {
            _flipX = flip;
            if (_isCompleted)
            {
                _spriteRenderer.flipX = flip;  
            }
        }

        public override void SetFlipY(bool flip)
        {
            _flipY = flip;
            if (_isCompleted)
            {
                _spriteRenderer.flipY = flip;
            }
        }

        public void SetPet(ScenePetEntity scenePet)
        {
            _scenePet = scenePet;
        }

        protected override void PostInstantiate()
        {
            base.PostInstantiate();
            _spriteTransform = _contentTransform.Find("Sprite");
            _spriteRenderer = _spriteTransform.GetComponent<SpriteRenderer>();
            
            _behaviorComponent = AddComponent<ScenePlayerBehaviorComponent>();
            _behaviorComponent.Setup(this);
            _behaviorComponent.SetTrackObject(_scenePet);
            
            OnPostInstantiateCompleted();
        }
        
        protected override void UpdateSortingLayer(int layerId)
        {
            base.UpdateSortingLayer(layerId);
            _spriteRenderer.sortingLayerID = layerId;
        }

        protected override void UpdateSortingOrder(int order)
        {
            base.UpdateSortingOrder(order);
            _spriteRenderer.sortingOrder = order;
        }
    }
}